C# 文字檔讀取、寫入基本用法


先指定檔案路徑

string filePath = @"檔案路徑";

接著使用StreamReader來讀取文字檔內容
並且定義一個string line來存取sr.ReadLine()逐行內容
如果有規律地讀取可以直接用while迴圈
也可以用if來指定要讀取的行

using (StreamReader sr = new StreamReader(filePath))
{
    string line;
    int lineNum = 1;
    while ((line = sr.ReadLine()) != null)
    {
        if(lineNum==/*指定行*/)
        {
        //要使用的內容=line;
        }
        lineNum++;
    }
    sr.Close();
}

同理寫入也是一樣道理

using (StreamWriter writer = new StreamWriter(filePath))
{
    writer.WriteLine(/*逐行寫入內容*/);
    writer.Close();
}

有想到新的方法再補充


更新:其實using可以自動關閉資源

#C# #Winform







你可能感興趣的文章

DOM - 事件傳遞機制

DOM - 事件傳遞機制

【THM Walkthrough】Enumerating Active Directory

【THM Walkthrough】Enumerating Active Directory

滲透測試重新打底(3.9)--論Web情蒐工具Shodan

滲透測試重新打底(3.9)--論Web情蒐工具Shodan






留言討論